from fastapi import APIRouter, HTTPException, Depends
from api.common import SearchRequest, SearchResult, get_vector_store

router = APIRouter(prefix="/search", tags=["搜索"])


@router.post("/", response_model=list[SearchResult])
async def search_documents(search: SearchRequest, vector_store=Depends(get_vector_store)):
    """搜索相似文档"""
    try:
        results = vector_store.search_similar_documents(search.query, search.top_k, search.category_id)
        # 添加category_ids字段到返回结果
        return [{"id": result[0], "content": result[1], "title": result[2], "similarity": float(result[3]), "category_ids": result[4]} for result in results]
    except Exception as e:
        raise HTTPException(status_code=400, detail=f"搜索失败: {str(e)}")